<?php

require_once 'DirectoryIterator.php';
require_once 'File.php';

function makeFileSystemObject($path)
{
	$args = func_get_args();
	if (count($args) > 1) {
		$o = new RL_FileSystem_Directory('/');
		$path = $o->joinPath($args);
	} else {
		$path = $args[0];
	}
	if (is_dir($path)) return new RL_FileSystem_Directory($path);
	if (is_file($path)) return new RL_FileSystem_File($path);
}


class RL_FileSystem_Directory implements Dir, ArrayAccess, IteratorAggregate
{
	public $path_separator = DIRECTORY_SEPARATOR;

	public function __construct ($path)
	{
		$this->setPath($path);
	} // end of __construct

	//* Dir 
	public function open ()
	{
		$this->iter = $this->getIterator();
	} // end of function open
	public function close ()
	{
		$this->iter->stop();
	} // end of function close
	public function read ()
	{
		if (isset($this->iter)) {
			return $this->iter->next();
		}
	} // end of function read
	public function eof ()
	{
		return isset($this->iter) && $this->iter->valid();
	} // end of function eof
	public function getPath ()
	{
		return $this->path;
	} // end of function getPath

	public function setPath ($value)
	{
		$this->path = $value;
		return $this;
	} // end of function setPath

	//* ArrayAccess
	public function offsetSet ($offset, $value)
	{
		throw RL_NotImplemented(__CLASS__.'::'.__FUNCTION__);
	} // end of function offsetSet
	public function offsetGet ($offset)
	{
		$path = $this->joinPath($this->getPath(), $offset);
		return makeFileSystemObject($path);
	} // end of function offsetGet
	public function offsetExists ($offset)
	{
		$path = $this->joinPath($this->getPath(), $offset);
		$o = makeFileSystemObject($path);
		return isset($o);
	} // end of function offsetExists
	public function offsetUnset ($offset)
	{
		throw RL_NotImplemented(__CLASS__.'::'.__FUNCTION__);
	} // end of function offsetUnset

	//* IteratorAggregate
	public function getIterator ()
	{
		return new RL_FileSystem_DirectoryIterator($this);
	} // end of function getIterator

	public function joinPath ()
	{
		$args = func_get_args();

		$path = '';
		foreach ($args as $name) {
			if (is_array($name)) {
				$path .= call_user_func_array(array($this, 'joinPath'), $name);
			} else {
				$path .= rtrim($name, $this->path_separator) . $this->path_separator;
			}
		}

		$path = rtrim($path, $this->path_separator);
		return $path;
	} // end of function joinPath

}

